package org.example.freeswitchdemo.listener;

import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.transport.message.EslMessage;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class FreeswitchHealthChecker {

    private final Client eslClient;

    public FreeswitchHealthChecker(Client eslClient) {
        this.eslClient = eslClient;
    }

    /**
     * 检查 FreeSWITCH 是否存活
     */
    public boolean isFreeswitchAlive() {
        try {
            EslMessage response = eslClient.sendSyncApiCommand("status", null);
            return response != null && !response.getBodyLines().isEmpty();
        } catch (Exception e) {
            return false;
        }
    }

    // 每 10 秒检测一次
    @Scheduled(fixedDelay = 3000)
    public void checkFreeswitch() {
        try {
            // 发送一个简单的命令，比如 status
            EslMessage response = eslClient.sendSyncApiCommand("status", null);

            if (response != null && !response.getBodyLines().isEmpty()) {
                System.out.println("✅ FreeSWITCH 存活，状态返回: " + response.getBodyLines().get(0));
            } else {
                System.err.println("⚠️ FreeSWITCH 未响应");
            }
        } catch (Exception e) {
            System.err.println("❌ 无法连接 FreeSWITCH: " + e.getMessage());
        }
    }
}

